﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.IO;
using System.Xml.Linq;

namespace ActivityTracker.Library
{
    public class FileSpliting
    {
        #region Global

        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream isoStream;
       
        List<FileEntity> result = null;
        List<FileEntity> list = new List<FileEntity>();

        #endregion
      
        public List<FileEntity> BackUpdataUsingFileSplitting(string deviceId)
        {

            if (isoStore.DirectoryExists("ActivityTracker"))
            {
                string fileString = System.IO.Path.GetFileName("*");
                string[] files = isoStore.GetFileNames("ActivityTracker/" + fileString);
                result = new List<FileEntity>();
                int fileno = 0;
                foreach (string file in files)
                {
                    string filename = "ActivityTracker/" + file;
                    if (isoStore.FileExists(filename))
                    {
                        fileno = fileno + 1;
                        isoStream = new IsolatedStorageFileStream(filename, FileMode.Open, isoStore);
                        
                        byte[] filestream = new byte[isoStream.Length];
                        isoStream.Read(filestream, 0, filestream.Length);
                        isoStream.Close();
                        list = Split(filestream, 10, filename, fileno);
                    }

                }
            }
            return list;
        }


        List<FileEntity> Split(byte[] filebytes, int range, string filename, int fileno)
        {
            range *= 1024;
            int pos = 0;
            int remaining;
            int Id = 0;
            int filecount = (int)Math.Ceiling((double)filebytes.Length / (range));
            while ((remaining = filebytes.Length - pos) > 0)
            {
                Id++;
                FileEntity fe = new FileEntity();
                fe.Id = Id;
                fe.FileName = filename;
                fe.FileCount = filecount;
                fe.FileNo = fileno;
                byte[] block = new byte[Math.Min(remaining, range)];

                Array.Copy(filebytes, pos, block, 0, block.Length);

                fe.Stream = block;
                result.Add(fe);
                pos += block.Length;
            }

            return result;
        }
    }
}
